<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/jexo/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/jexo/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/jexo/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/jexo/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/jexo/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/jexo/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/jexo/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Android,源码分析," />










<meta name="description" content="在刚开始接触Android的时候就尝试着去看ActivityThread，希望能明白App的启动流程。毋庸置疑，当时是以失败而告终的。现在又卷土重来，重新尝试着去看，发现以前困惑的地方都豁然开朗了。当然，也是阅读了一些优秀的文章的。那么为什么我在这里又写一篇呢？是他们写的不好么，并不是的，而是希望能把自己遇到的一些困惑的地方和自己的理解与大家一起分享下，希望能帮到大家。">
<meta name="keywords" content="Android,源码分析">
<meta property="og:type" content="article">
<meta property="og:title" content="Android App 启动流程">
<meta property="og:url" content="http://ja_project.gitee.io/jexo/2018/04/18/AndroidApp启动流程/index.html">
<meta property="og:site_name" content="Ling Hu Blog">
<meta property="og:description" content="在刚开始接触Android的时候就尝试着去看ActivityThread，希望能明白App的启动流程。毋庸置疑，当时是以失败而告终的。现在又卷土重来，重新尝试着去看，发现以前困惑的地方都豁然开朗了。当然，也是阅读了一些优秀的文章的。那么为什么我在这里又写一篇呢？是他们写的不好么，并不是的，而是希望能把自己遇到的一些困惑的地方和自己的理解与大家一起分享下，希望能帮到大家。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-04-18T13:21:24.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android App 启动流程">
<meta name="twitter:description" content="在刚开始接触Android的时候就尝试着去看ActivityThread，希望能明白App的启动流程。毋庸置疑，当时是以失败而告终的。现在又卷土重来，重新尝试着去看，发现以前困惑的地方都豁然开朗了。当然，也是阅读了一些优秀的文章的。那么为什么我在这里又写一篇呢？是他们写的不好么，并不是的，而是希望能把自己遇到的一些困惑的地方和自己的理解与大家一起分享下，希望能帮到大家。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/jexo/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://ja_project.gitee.io/jexo/2018/04/18/AndroidApp启动流程/"/>





  <title>Android App 启动流程 | Ling Hu Blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?abc8796c232e2b898d516245257842b4";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/jexo/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Ling Hu Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/jexo/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/jexo/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/jexo/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/jexo/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/jexo/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://ja_project.gitee.io/jexo/jexo/2018/04/18/AndroidApp启动流程/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Ling Hu">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/jexo/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Ling Hu Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Android App 启动流程</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-04-18T20:59:33+08:00">
                2018-04-18
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/jexo/categories/Android源码/" itemprop="url" rel="index">
                    <span itemprop="name">Android源码</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/jexo/2018/04/18/AndroidApp启动流程/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count gitment-comments-count" data-xid="/jexo/2018/04/18/AndroidApp启动流程/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>在刚开始接触Android的时候就尝试着去看<code>ActivityThread</code>，希望能明白App的启动流程。毋庸置疑，当时是以失败而告终的。现在又卷土重来，重新尝试着去看，发现以前困惑的地方都豁然开朗了。当然，也是阅读了一些优秀的文章的。<br>那么为什么我在这里又写一篇呢？是他们写的不好么，并不是的，而是希望能把自己遇到的一些困惑的地方和自己的理解与大家一起分享下，希望能帮到大家。</p>
<a id="more"></a>
<p>下面是我参考的博客，没错，就是老罗的。<br><a href="http://blog.csdn.net/luoshengyang/article/details/6689748" target="_blank" rel="noopener">http://blog.csdn.net/luoshengyang/article/details/6689748</a></p>
<p> 写的非常详细，但是自己没有去看过，跟踪过源码跳转，是很难看懂的。所以不管是看上面的博客，还是看我这篇文章，你至少要先自己一步步跟踪过代码。</p>
<pre><code>注意：Android源码 2.3.1
</code></pre><p>下面开始分享：</p>
<h4 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h4><ol>
<li>手机整个桌面其实也是一个应用程序，叫Launcher，继承Activity</li>
<li>点击Launcher下的桌面图标，触发onClick事件，才是我们要看的第一个入口</li>
<li>每个应用程序有自己的ActivityThread,Launcher也是</li>
<li>ActivityManagerProxy与ActivityManagerService是一对Binder</li>
<li>ApplicationThread与ActivityThreadProxy是一对Binder</li>
<li>ActivityManagerProxy和ApplicationThread是应用程序进程中使用</li>
<li>ApplicationThreadProxy是在ActivityManagerService中使用</li>
<li>ActivityManagerService只存在一个，在系统启动的时候，就已创建</li>
</ol>
<p>基本上看到这里还没晕的话，已经很强了。下面继续。</p>
<h4 id="我所在意的几件事"><a href="#我所在意的几件事" class="headerlink" title="我所在意的几件事"></a>我所在意的几件事</h4><h5 id="ActivityThread是什么时候创建的"><a href="#ActivityThread是什么时候创建的" class="headerlink" title="ActivityThread是什么时候创建的"></a>ActivityThread是什么时候创建的</h5><p>既然说了每个应用程序都有自己的一个ActivityThread,那么我最关心的肯定是这个ActivityThread到底是什么时候创建的。如果你通过跟踪代码一步步跟入，其实是很难跟到这一步的，因为里面有太多的if判断，分支多，代码长。</p>
<p>我指下位置：<br>framework/base/services/java/com/android/server/am/ActivityManagerService.java<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">  <span class="function"><span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">startProcessLocked</span><span class="params">(ProcessRecord app,</span></span></span><br><span class="line"><span class="function"><span class="params">            String hostingType, String hostingNameStr)</span> </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">    <span class="keyword">int</span> pid = Process.start(<span class="string">"android.app.ActivityThread"</span>,</span><br><span class="line">                    mSimpleProcessManagement ? app.processName : <span class="keyword">null</span>, uid, uid,</span><br><span class="line">                    gids, debugFlags, <span class="keyword">null</span>);</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>我简单的说下流程。</p>
<p>一开始所在的进程是Launcher所在的进程，Launcher有自己的ActivityThread,也有就是说有自己的ApplicationThread,ActivityManagerProxy,ApplicationThreadProxy来与ActivityManagerService进行交互。当我们在Launcher中点击一个App图标，Launcher就监测到onClick事件，然后与ActivityManagerService进行交互后(这里交互有几个步骤，我这不具体细说，可以看看我上面推荐的博客),告诉ActivityManagerService可以启动这个App的MainActivity了，然后一判断，发现这个MainActivity还没有自己的ActivityThread然后就启动。</p>
<p>步骤很多，但是我前面也说过，我这篇文章不会写太大篇幅贴代码，然后去分析，因为老罗的blog确实很详细了，我主要是想把我当时遇到的问题给大家分享一下，我当时就是一直找不到ActivityThread他到底是在哪里启动的。</p>
<h5 id="ActivityManagerProxy-ApplicationThread-ApplicationThreadProxy哪里创建"><a href="#ActivityManagerProxy-ApplicationThread-ApplicationThreadProxy哪里创建" class="headerlink" title="ActivityManagerProxy,ApplicationThread,ApplicationThreadProxy哪里创建"></a>ActivityManagerProxy,ApplicationThread,ApplicationThreadProxy哪里创建</h5><p>前面也简单的介绍了，我们的App正是通过这3个类与ActivityManagerService进行交互的，把他们搞懂的，差不多已经对整个流程理解了一半了，确实是这样，第一次阅读这个源码的时候，我就是很难理解他们的关系，所以有些地方一直无法走通，导致半途而废。所以，为了弄懂这3个类，首先第一步我们要了解这3个类分别是在哪里创建的，对我们理解也会有一些帮助。</p>
<p>ApplicationThread创建：<br>framework/base/core/java/android/app/ActivityThread.java<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">ActivityThread</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    ...</span><br><span class="line">    <span class="keyword">final</span> ApplicationThread mAppThread = <span class="keyword">new</span> ApplicationThread();</span><br><span class="line">    ...</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        ...</span><br><span class="line">        ActivityThread thread = <span class="keyword">new</span> ActivityThread();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>启动ActivityTread，先进入main函数，然后创建<code>ActivityThread</code>,ApplicationThread就会被创建。</p>
<p>ActivityManagerProxy创建:<br>framework/base/core/java/android/app/ActivityThread.java<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">ActivityThread</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">attach</span><span class="params">(<span class="keyword">boolean</span> system)</span> </span>&#123;</span><br><span class="line">        ...</span><br><span class="line">        IActivityManager mgr = ActivityManagerNative.getDefault();</span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        ...</span><br><span class="line">        ActivityThread thread = <span class="keyword">new</span> ActivityThread();</span><br><span class="line">        thread.attach(<span class="keyword">false</span>);</span><br><span class="line">        ...</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>framework/base/core/java/android/app/ActivityManagerNative.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">ActivityManagerNative</span> <span class="keyword">extends</span> <span class="title">Binder</span> <span class="keyword">implements</span> <span class="title">IActivityManager</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">public</span> IActivityManager <span class="title">asInterface</span><span class="params">(IBinder obj)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (obj == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        IActivityManager in =</span><br><span class="line">            (IActivityManager)obj.queryLocalInterface(descriptor);</span><br><span class="line">        <span class="keyword">if</span> (in != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> in;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> ActivityManagerProxy(obj);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Retrieve the system's default/global activity manager.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">public</span> IActivityManager <span class="title">getDefault</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (gDefault != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="comment">//if (Config.LOGV) Log.v(</span></span><br><span class="line">            <span class="comment">//    "ActivityManager", "returning cur default = " + gDefault);</span></span><br><span class="line">            <span class="keyword">return</span> gDefault;</span><br><span class="line">        &#125;</span><br><span class="line">        IBinder b = ServiceManager.getService(<span class="string">"activity"</span>);</span><br><span class="line">        <span class="keyword">if</span> (Config.LOGV) Log.v(</span><br><span class="line">            <span class="string">"ActivityManager"</span>, <span class="string">"default service binder = "</span> + b);</span><br><span class="line">        gDefault = asInterface(b);</span><br><span class="line">        <span class="keyword">if</span> (Config.LOGV) Log.v(</span><br><span class="line">            <span class="string">"ActivityManager"</span>, <span class="string">"default service = "</span> + gDefault);</span><br><span class="line">        <span class="keyword">return</span> gDefault;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    ...</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>创建好ActivityThread对象后会执行attach方法，然后在里面调用ActivityManagerNative.getDefault()方法，<br>ActivityManagerProxy是ActivityManagerNative的子类，最终会在asInterface方法中new一个ActivityManagerProxy。值得关注的是，在new ActivityManagerProxy的时候传入一个Binder。我们再看getDefault方法，其实这个Binder就是 ServiceManager.getService(“activity”)，也就是ActivityManagerService。</p>
<p>ApplicationThreadProxy创建：</p>
<p>framework/base/core/java/android/app/ActivityThread.java<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">ActivityThread</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">attach</span><span class="params">(<span class="keyword">boolean</span> system)</span> </span>&#123;</span><br><span class="line">        ...</span><br><span class="line">        IActivityManager mgr = ActivityManagerNative.getDefault();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                mgr.attachApplication(mAppThread);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (RemoteException ex) &#123;</span><br><span class="line">       &#125;</span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        ...</span><br><span class="line">        ActivityThread thread = <span class="keyword">new</span> ActivityThread();</span><br><span class="line">        thread.attach(<span class="keyword">false</span>);</span><br><span class="line">        ...</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>framework/base/core/java/android/app/ActivityManagerNative.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">ActivityManagerNative</span> <span class="keyword">extends</span> <span class="title">Binder</span> <span class="keyword">implements</span> <span class="title">IActivityManager</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line"></span><br><span class="line">  ...</span><br><span class="line">  <span class="keyword">case</span> ATTACH_APPLICATION_TRANSACTION: &#123;</span><br><span class="line">            data.enforceInterface(IActivityManager.descriptor);</span><br><span class="line">            IApplicationThread app = ApplicationThreadNative.asInterface(</span><br><span class="line">                    data.readStrongBinder());</span><br><span class="line">            <span class="keyword">if</span> (app != <span class="keyword">null</span>) &#123;</span><br><span class="line">                attachApplication(app);</span><br><span class="line">            &#125;</span><br><span class="line">            reply.writeNoException();</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">  ...</span><br><span class="line">  ...</span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">attachApplication</span><span class="params">(IApplicationThread app)</span> <span class="keyword">throws</span> RemoteException</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        Parcel data = Parcel.obtain();</span><br><span class="line">        Parcel reply = Parcel.obtain();</span><br><span class="line">        data.writeInterfaceToken(IActivityManager.descriptor);</span><br><span class="line">        data.writeStrongBinder(app.asBinder());</span><br><span class="line">        mRemote.transact(ATTACH_APPLICATION_TRANSACTION, data, reply, <span class="number">0</span>);</span><br><span class="line">        reply.readException();</span><br><span class="line">        data.recycle();</span><br><span class="line">        reply.recycle();</span><br><span class="line">    &#125;</span><br><span class="line">   ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>framework/base/core/java/android/app/ApplicationThreadNative.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">ApplicationThreadNative</span> <span class="keyword">extends</span> <span class="title">Binder</span></span></span><br><span class="line"><span class="class">        <span class="keyword">implements</span> <span class="title">IApplicationThread</span> </span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Cast a Binder object into an application thread interface, generating</span></span><br><span class="line"><span class="comment">     * a proxy if needed.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">public</span> IApplicationThread <span class="title">asInterface</span><span class="params">(IBinder obj)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (obj == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        IApplicationThread in =</span><br><span class="line">            (IApplicationThread)obj.queryLocalInterface(descriptor);</span><br><span class="line">        <span class="keyword">if</span> (in != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> in;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> ApplicationThreadProxy(obj);</span><br><span class="line">    &#125;</span><br><span class="line">    ...</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>ApplicationThreadProxy的创建是最复杂的，一共涉及到了3个文件，其中最关键的还是在<code>ActivityManagerNative</code>中的调用。已经设计到了跨进程通信，我在后面再详细描述。</p>
<h5 id="上面3个类的作用"><a href="#上面3个类的作用" class="headerlink" title="上面3个类的作用"></a>上面3个类的作用</h5><p>其实在<code>前言</code>中我已经对他们的关系做好简单的描述，下面我们再看下。</p>
<ol>
<li>ActivityManagerProxy与ActivityManagerService是一对Binder</li>
<li>ApplicationThread与ActivityThreadProxy是一对Binder</li>
<li>ActivityManagerProxy和ApplicationThread是应用程序进程中使用</li>
<li>ApplicationThreadProxy是在ActivityManagerService中使用</li>
</ol>
<p>一对Binder的作用是，这2个Binder分别处在不同的进程，如果要进行通信，就要write，read等方法，也就是Binder机制，这个机制在这里我不过多介绍，因为对整个流程来说，你只要知道，我们跨进程是用它来实现的就可以了，并不需要去了解实现的细节。</p>
<p>我这里可能还说的不够明确，那么我再明确一下。</p>
<pre><code>ActivityManagerService与我们的App处在不同的进程。这意味着，ActivityManagerService要给我们App发送一个消息只能通过ApplicationThreadProxy，然后我们在ApplicationThread这个对象中读取到ApplicationThreadProxy通过Binder机制传过来的数据，然后进行处理。同理，我们App要与另外一个进程中的ActivityManagerService只能通过ActivityManagerProxy来实现，因为他们是一对Binder，在创建的时候就已经进行了绑定。
</code></pre><h6 id="这3个类到底是怎么与ActivityManagerService交互的，来个demo"><a href="#这3个类到底是怎么与ActivityManagerService交互的，来个demo" class="headerlink" title="这3个类到底是怎么与ActivityManagerService交互的，来个demo"></a>这3个类到底是怎么与ActivityManagerService交互的，来个demo</h6><p>交互流程很复杂很多，大家都知道<code>Activity</code>有很多生命周期函数，其实都是这几者之间交互的时候发生的，所以我不过多介绍，带大家走一个来回的交互，还是从<code>ActivityThread</code>这个入口开始。</p>
<p>framework/base/core/java/android/app/ActivityThread.java<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">ActivityThread</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">attach</span><span class="params">(<span class="keyword">boolean</span> system)</span> </span>&#123;</span><br><span class="line">        ...</span><br><span class="line">        IActivityManager mgr = ActivityManagerNative.getDefault();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                mgr.attachApplication(mAppThread);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (RemoteException ex) &#123;</span><br><span class="line">       &#125;</span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        ...</span><br><span class="line">        ActivityThread thread = <span class="keyword">new</span> ActivityThread();</span><br><span class="line">        thread.attach(<span class="keyword">false</span>);</span><br><span class="line">        ...</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>framework/base/core/java/android/app/ActivityManagerNative.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">ActivityManagerNative</span> <span class="keyword">extends</span> <span class="title">Binder</span> <span class="keyword">implements</span> <span class="title">IActivityManager</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line"></span><br><span class="line">  ...</span><br><span class="line">  <span class="keyword">case</span> ATTACH_APPLICATION_TRANSACTION: &#123;</span><br><span class="line">            data.enforceInterface(IActivityManager.descriptor);</span><br><span class="line">            IApplicationThread app = ApplicationThreadNative.asInterface(</span><br><span class="line">                    data.readStrongBinder());</span><br><span class="line">            <span class="keyword">if</span> (app != <span class="keyword">null</span>) &#123;</span><br><span class="line">                attachApplication(app);</span><br><span class="line">            &#125;</span><br><span class="line">            reply.writeNoException();</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">  ...</span><br><span class="line">  ...</span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">attachApplication</span><span class="params">(IApplicationThread app)</span> <span class="keyword">throws</span> RemoteException</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        Parcel data = Parcel.obtain();</span><br><span class="line">        Parcel reply = Parcel.obtain();</span><br><span class="line">        data.writeInterfaceToken(IActivityManager.descriptor);</span><br><span class="line">        data.writeStrongBinder(app.asBinder());</span><br><span class="line">        mRemote.transact(ATTACH_APPLICATION_TRANSACTION, data, reply, <span class="number">0</span>);</span><br><span class="line">        reply.readException();</span><br><span class="line">        data.recycle();</span><br><span class="line">        reply.recycle();</span><br><span class="line">    &#125;</span><br><span class="line">   ...</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ActivityManagerProxy</span> <span class="keyword">implements</span> <span class="title">IActivityManager</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ActivityManagerProxy</span><span class="params">(IBinder remote)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        mRemote = remote;</span><br><span class="line">    &#125;</span><br><span class="line">｝</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里代码是关键，我们在ActivityThread中调用attachApplication，mRemote其实就是就是在创建ActivityManagerProxy传入的Binder，前面也介绍了，其实也就是ActivityManagerService。因为ActivityManagerService是继承ActivityManagerNative的，ActivityManagerNative继承了Binder.<br>在attachApplication方法中调用mRemote.transact(),其实是调用了Binder的transact方法。</p>
<p>framework/base/core/java/android/os/Binder.java<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">/**</span><br><span class="line">     * Default implementation rewinds the parcels and calls onTransact.  On</span><br><span class="line">     * the remote side, transact calls into the binder to do the IPC.</span><br><span class="line">     */</span><br><span class="line">    public final boolean transact(int code, Parcel data, Parcel reply,</span><br><span class="line">            int flags) throws RemoteException &#123;</span><br><span class="line">        if (Config.LOGV) Log.v(&quot;Binder&quot;, &quot;Transact: &quot; + code + &quot; to &quot; + this);</span><br><span class="line">        if (data != null) &#123;</span><br><span class="line">            data.setDataPosition(0);</span><br><span class="line">        &#125;</span><br><span class="line">        boolean r = onTransact(code, data, reply, flags);</span><br><span class="line">        if (reply != null) &#123;</span><br><span class="line">            reply.setDataPosition(0);</span><br><span class="line">        &#125;</span><br><span class="line">        return r;</span><br><span class="line">    &#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure></p>
<p>最终触发了<code>onTransact</code>方法。我们这里首先要明白调用transact的是ActivityManagerService。所以，当我们运行到这里的时候其实已经切换到了ActivityManagerService所在的进程。</p>
<p>然后我们再进入下一步。因为在ActivityManagerNative中，对Binder的onTransact重写，所以我们最终触发的是在ActivityManagerNative中的onTransact方法。</p>
<p>framework/base/core/java/android/app/ActivityManagerNative.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">...</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onTransact</span><span class="params">(<span class="keyword">int</span> code, Parcel data, Parcel reply, <span class="keyword">int</span> flags)</span></span></span><br><span class="line"><span class="function">            <span class="keyword">throws</span> RemoteException </span>&#123;</span><br><span class="line">        <span class="keyword">switch</span> (code) &#123;</span><br><span class="line"></span><br><span class="line">        ...</span><br><span class="line">        <span class="keyword">case</span> ATTACH_APPLICATION_TRANSACTION: &#123;</span><br><span class="line">            data.enforceInterface(IActivityManager.descriptor);</span><br><span class="line">            IApplicationThread app = ApplicationThreadNative.asInterface(</span><br><span class="line">                    data.readStrongBinder());</span><br><span class="line">            <span class="keyword">if</span> (app != <span class="keyword">null</span>) &#123;</span><br><span class="line">                attachApplication(app);</span><br><span class="line">            &#125;</span><br><span class="line">            reply.writeNoException();</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        ...</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>
<p>在前面调用transact方法时传入了code，<code>ATTACH_APPLICATION_TRANSACTION</code>。其实在前面介绍那3个重要的类中的ApplicationThreadProxy的创建过程的时候，也是这里的代码，没错，这里是非常重要的一步，因为在这里创建了ApplicationThreadProxy这个类，有了这个类，ActivityManagerService才能与我们的App进行交互。</p>
<p>我们其实可以回顾下，ActivityManagerProxy的创建，new的时候是传入了ActivityManagerService的，也就是另一个Binder。这样才能把2者绑定，相互读写数据。同理，ApplicationThreadProxy创建的时候，也应该是传入一个Binder，既然前面说了ApplicationThreadProxy与ApplicationThread是一对，那么就应该传入ApplicationThread。data.readStrongBinder() 这里读取到的，也就是我们App进程通过Binder机制传过来的，其实就是我们需要的ApplicationThread。</p>
<p>接下来，也就是最关键的一步，其实也是我在第一次阅读源码的时候卡住的时候。</p>
<p>调用attachApplication方法。一般情况下，我们就直接搜索这个方法，发现在当前这个类ActivityManagerNative下就有这个方法，就是我们刚才已经调用过的方法。</p>
<p>framework/base/core/java/android/app/ActivityManagerNative.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">ActivityManagerNative</span> <span class="keyword">extends</span> <span class="title">Binder</span> <span class="keyword">implements</span> <span class="title">IActivityManager</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line"></span><br><span class="line">  ...</span><br><span class="line">  ...</span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">attachApplication</span><span class="params">(IApplicationThread app)</span> <span class="keyword">throws</span> RemoteException</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        Parcel data = Parcel.obtain();</span><br><span class="line">        Parcel reply = Parcel.obtain();</span><br><span class="line">        data.writeInterfaceToken(IActivityManager.descriptor);</span><br><span class="line">        data.writeStrongBinder(app.asBinder());</span><br><span class="line">        mRemote.transact(ATTACH_APPLICATION_TRANSACTION, data, reply, <span class="number">0</span>);</span><br><span class="line">        reply.readException();</span><br><span class="line">        data.recycle();</span><br><span class="line">        reply.recycle();</span><br><span class="line">    &#125;</span><br><span class="line">   ...</span><br><span class="line"></span><br><span class="line">哎，这里好奇怪，我已经通过Binder机制把数据传给ActivityManagerService了，怎么又重复调用这个attachApplication方法，又要传一遍数据么，感觉无限死循环了呀。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">前面我已经说了，当前其实是在ActivityManagerService下了，所以应该调用的是ActivityManagerService下的</span><br><span class="line">attachApplication方法，虽然ActivityManagerService是ActivityManagerNative的子类，但是他对attachApplication这个方法进行了重写。</span><br><span class="line"></span><br><span class="line">framework/base/services/java/com/android/server/am/ActivityManagerService.java</span><br><span class="line">```java</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">boolean</span> <span class="title">attachApplicationLocked</span><span class="params">(IApplicationThread thread,</span></span></span><br><span class="line"><span class="function"><span class="params">            <span class="keyword">int</span> pid)</span> </span>&#123;</span><br><span class="line">        ...</span><br><span class="line">        thread.bindApplication(processName, app.instrumentationInfo != <span class="keyword">null</span></span><br><span class="line">                    ? app.instrumentationInfo : app.info, providers,</span><br><span class="line">                    app.instrumentationClass, app.instrumentationProfileFile,</span><br><span class="line">                    app.instrumentationArguments, app.instrumentationWatcher, testMode,</span><br><span class="line">                    isRestrictedBackupMode || !normalMode,</span><br><span class="line">                    mConfiguration, getCommonServicesLocked());</span><br><span class="line">        ...</span><br><span class="line">&#125;</span><br><span class="line">...</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">attachApplication</span><span class="params">(IApplicationThread thread)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</span><br><span class="line">            <span class="keyword">int</span> callingPid = Binder.getCallingPid();</span><br><span class="line">            <span class="keyword">final</span> <span class="keyword">long</span> origId = Binder.clearCallingIdentity();</span><br><span class="line">            attachApplicationLocked(thread, callingPid);</span><br><span class="line">            Binder.restoreCallingIdentity(origId);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">...</span><br></pre></td></tr></table></figure>
<p>走到这一步了，基本上接下来就差不多了。</p>
<p>thread其实就是ApplicationThreadProxy，这里就是ActivityManagerService通知我们App绑定Application。<br>首先我们要搞清楚，我们调用的是ApplicationThreadProxy的bindApplication。因为我们App端的ApplicationThread也有bindApplication这个方法。</p>
<p>所以这里有个很重要的提示，一定要搞清楚这2对Binder到底是在调用谁，因为他们里面的方法都是类似的，你一个搞混了，接下来是走不下去的。</p>
<p>framework/base/core/java/android/ApplicationThreadNative.java<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">...</span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onTransact</span><span class="params">(<span class="keyword">int</span> code, Parcel data, Parcel reply, <span class="keyword">int</span> flags)</span></span></span><br><span class="line"><span class="function">            <span class="keyword">throws</span> RemoteException </span>&#123;</span><br><span class="line">        <span class="keyword">switch</span> (code) &#123;</span><br><span class="line">            <span class="keyword">case</span> BIND_APPLICATION_TRANSACTION:</span><br><span class="line">        &#123;</span><br><span class="line">            data.enforceInterface(IApplicationThread.descriptor);</span><br><span class="line">            String packageName = data.readString();</span><br><span class="line">            ApplicationInfo info =</span><br><span class="line">                ApplicationInfo.CREATOR.createFromParcel(data);</span><br><span class="line">            List&lt;ProviderInfo&gt; providers =</span><br><span class="line">                data.createTypedArrayList(ProviderInfo.CREATOR);</span><br><span class="line">            ComponentName testName = (data.readInt() != <span class="number">0</span>)</span><br><span class="line">                ? <span class="keyword">new</span> ComponentName(data) : <span class="keyword">null</span>;</span><br><span class="line">            String profileName = data.readString();</span><br><span class="line">            Bundle testArgs = data.readBundle();</span><br><span class="line">            IBinder binder = data.readStrongBinder();</span><br><span class="line">            IInstrumentationWatcher testWatcher = IInstrumentationWatcher.Stub.asInterface(binder);</span><br><span class="line">            <span class="keyword">int</span> testMode = data.readInt();</span><br><span class="line">            <span class="keyword">boolean</span> restrictedBackupMode = (data.readInt() != <span class="number">0</span>);</span><br><span class="line">            Configuration config = Configuration.CREATOR.createFromParcel(data);</span><br><span class="line">            HashMap&lt;String, IBinder&gt; services = data.readHashMap(<span class="keyword">null</span>);</span><br><span class="line">            bindApplication(packageName, info,</span><br><span class="line">                            providers, testName, profileName,</span><br><span class="line">                            testArgs, testWatcher, testMode, restrictedBackupMode,</span><br><span class="line">                            config, services);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        ｝</span><br><span class="line">    ｝</span><br><span class="line"></span><br><span class="line">...</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">bindApplication</span><span class="params">(String packageName, ApplicationInfo info,</span></span></span><br><span class="line"><span class="function"><span class="params">            List&lt;ProviderInfo&gt; providers, ComponentName testName,</span></span></span><br><span class="line"><span class="function"><span class="params">            String profileName, Bundle testArgs, IInstrumentationWatcher testWatcher, <span class="keyword">int</span> debugMode,</span></span></span><br><span class="line"><span class="function"><span class="params">            <span class="keyword">boolean</span> restrictedBackupMode, Configuration config,</span></span></span><br><span class="line"><span class="function"><span class="params">            Map&lt;String, IBinder&gt; services)</span> <span class="keyword">throws</span> RemoteException </span>&#123;</span><br><span class="line">        Parcel data = Parcel.obtain();</span><br><span class="line">        data.writeInterfaceToken(IApplicationThread.descriptor);</span><br><span class="line">        data.writeString(packageName);</span><br><span class="line">        info.writeToParcel(data, <span class="number">0</span>);</span><br><span class="line">        data.writeTypedList(providers);</span><br><span class="line">        <span class="keyword">if</span> (testName == <span class="keyword">null</span>) &#123;</span><br><span class="line">            data.writeInt(<span class="number">0</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            data.writeInt(<span class="number">1</span>);</span><br><span class="line">            testName.writeToParcel(data, <span class="number">0</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        data.writeString(profileName);</span><br><span class="line">        data.writeBundle(testArgs);</span><br><span class="line">        data.writeStrongInterface(testWatcher);</span><br><span class="line">        data.writeInt(debugMode);</span><br><span class="line">        data.writeInt(restrictedBackupMode ? <span class="number">1</span> : <span class="number">0</span>);</span><br><span class="line">        config.writeToParcel(data, <span class="number">0</span>);</span><br><span class="line">        data.writeMap(services);</span><br><span class="line">        mRemote.transact(BIND_APPLICATION_TRANSACTION, data, <span class="keyword">null</span>,</span><br><span class="line">                IBinder.FLAG_ONEWAY);</span><br><span class="line">        data.recycle();</span><br><span class="line">    &#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure></p>
<p>同理，这里的mRemote其实就是绑定的另一个Binder，也就是ApplicationThread，这里是ActivityManagerService利用ApplicationThreadProxy给ApplicationThread 传递消息。<br>然后在onTransact方法中接收到ApplicationThreadProxy传来的数据，然后调用ApplicationThread中的bindApplication方法，跟前面ActivityManagerProxy传递消息给ActivityManagerService的代码差不多的，我就不过多介绍了。接下来已经是在我们的App进程中了，得到ActivityManagerService消息之后的一些处理，这里我就不讲了。</p>
<p>到此为止，一来一回，详细的介绍了App进程与ActivityManagerService的交互过程。</p>
<h4 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h4><p>首先还是要自己先跟一遍源码，然后哪里卡住了，再看书，看文章，解决之后自己再跟一遍，这样就能对整个流程有较深刻的认识了。</p>
<p>源码还是要看的，万一以后要写个操作系统呢～</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>Donate comment here</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/jexo/images/wechatpay.png" alt="Ling Hu 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/jexo/images/alipay.png" alt="Ling Hu 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/jexo/tags/Android/" rel="tag"># Android</a>
          
            <a href="/jexo/tags/源码分析/" rel="tag"># 源码分析</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/jexo/2018/04/18/Android HAL层开发/" rel="next" title="Android HAL层开发">
                <i class="fa fa-chevron-left"></i> Android HAL层开发
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/jexo/2018/04/18/抓取起点免费小说/" rel="prev" title="抓取起点免费小说">
                抓取起点免费小说 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      
        <div id="gitment-container"></div>
      
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/jexo/images/avatar.jpg"
                alt="Ling Hu" />
            
              <p class="site-author-name" itemprop="name">Ling Hu</p>
              <p class="site-description motion-element" itemprop="description">Android,源码解析,每天进步一点点</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/jexo/archives/">
              
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/jexo/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/jexo/tags/index.html">
                  <span class="site-state-item-count">14</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/javalong" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#我所在意的几件事"><span class="nav-number">2.</span> <span class="nav-text">我所在意的几件事</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#ActivityThread是什么时候创建的"><span class="nav-number">2.1.</span> <span class="nav-text">ActivityThread是什么时候创建的</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#ActivityManagerProxy-ApplicationThread-ApplicationThreadProxy哪里创建"><span class="nav-number">2.2.</span> <span class="nav-text">ActivityManagerProxy,ApplicationThread,ApplicationThreadProxy哪里创建</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#上面3个类的作用"><span class="nav-number">2.3.</span> <span class="nav-text">上面3个类的作用</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#这3个类到底是怎么与ActivityManagerService交互的，来个demo"><span class="nav-number">2.3.1.</span> <span class="nav-text">这3个类到底是怎么与ActivityManagerService交互的，来个demo</span></a></li></ol></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#总结"><span class="nav-number">3.</span> <span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Ling Hu</span>

  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/jexo/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/jexo/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/jexo/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/jexo/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/jexo/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/jexo/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/jexo/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/jexo/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/jexo/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/jexo/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/jexo/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  







<!-- LOCAL: You can save these files to your site and update links -->
    
        
        <link rel="stylesheet" href="https://aimingoo.github.io/gitmint/style/default.css">
        <script src="https://aimingoo.github.io/gitmint/dist/gitmint.browser.js"></script>
    
<!-- END LOCAL -->

    
      <style>
        a.gitment-editor-footer-tip { display: none; }
        .gitment-container.gitment-footer-container { display: none; }
      </style>
    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitmint({
            id: getId(),
            owner: 'javalong',
            repo: 'RxJava-Operator',
            
            lang: "zh-Hans" || navigator.language || navigator.systemLanguage || navigator.userLanguage,
            
            oauth: {
            
            
                client_secret: '06b042e57b8420f5002a6407348dde078bcde761',
            
                client_id: '1b5481d6512b2f28d7a2'
            }});
        gitment.render('gitment-container');
      }

      function getId(){
            if( window.location.pathname.length>=50){
                return window.location.pathname.substr(0,50)
            }else{
                return window.location.pathname
            }
      }

      
      renderGitment();
      
      </script>
    







  





  

  

  

  
  

  

  

  

</body>
</html>
